package edu.upc.dew.filter;

import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonpFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        
        String cbfn = request.getParameter("callback");
        
        if(null != cbfn) {
            OutputStream out = res.getOutputStream();
            GenericResponseWrapper wrapper = new GenericResponseWrapper(res);
            chain.doFilter(request, wrapper);
            out.write((cbfn + "(").getBytes());
            out.write(wrapper.getData());
            out.write(");".getBytes());
            wrapper.setContentType("text/javascript;charset=UTF-8");
            out.close();
        }
    }

    @Override
    public void destroy() {
    }

}
